import { Controller, Post, Req, UploadedFile, UseInterceptors,BadRequestException } from '@nestjs/common';
 import { FileInterceptor } from '@nestjs/platform-express';
 import { Request } from 'express';
 import { success } from '@/utils';

 @Controller('upload')

 export class FileUploadController {

 @UseInterceptors(FileInterceptor('file'))

 @Post('single')
 uploadFile(@UploadedFile() file: Express.Multer.File, @Req() req: Request) {
  if (!file) {
      throw new BadRequestException('未上传文件');
  }

  // 安全地获取客户端域名、端口和协议
  const hostname = this.getSafeHeader(req, 'x-forwarded-host') || req.hostname;
  const port = this.getSafeHeader(req, 'x-forwarded-port') || req.socket.localPort;
  const protocol = this.getSafeHeader(req, 'x-forwarded-proto') || req.protocol;
  // 防止路径注入，清理并规范化文件路径
  const sanitizedPath = this.sanitizeFilePath(file.path);

  // 构造最终的文件访问 URL
  const fileUrl = `${protocol}://${hostname}:${port}/${sanitizedPath}`;

  // 返回结果
  return success({ ...file, path: fileUrl }, '上传成功');
}
// 辅助方法：安全地获取请求头
private getSafeHeader(req: Request, headerName: string): string | undefined {
  const headerValue = req.headers[headerName];
  if (typeof headerValue === 'string') {
      return headerValue.trim();
  }
  return undefined;
}

// 辅助方法：清理文件路径，防止路径注入
private sanitizeFilePath(filePath: string): string {
  // 替换反斜杠为正斜杠，并移除多余的路径部分
  let cleanedPath = filePath.replace(/\\/g, '/');
  return cleanedPath;
}

 }